package com.gopay.bis.cbrmb.server;
import java.io.IOException;
import java.net.ServerSocket;
import java.net.Socket;
import java.util.Map;

import javax.servlet.ServletContext;

import org.slf4j.Logger;
import org.slf4j.LoggerFactory;
import org.springframework.context.ApplicationContext;
import org.springframework.web.context.support.WebApplicationContextUtils;

import com.gopay.bis.cbrmb.listener.CbRmbServerSocketListener;

/**
 * 
 * @ClassName: CbRmbSocketThread 
 * @Description: 单独启动一个线程去等待客户端连接 
 * @author gd.cui 
 * @date 2016年7月11日 上午11:44:49 ww.gopay.com.cn Inc.All rights reserved.
 */
public class CbRmbSocketThread extends Thread {
    
    private static final Logger logger = LoggerFactory.getLogger(CbRmbServerSocketListener.class);
    private ServletContext servletContext;

    private ServerSocket serverSocket;
	
	private Map<String, String> cbrConfig;

    @SuppressWarnings("unchecked")
	public void init() {
    	ApplicationContext context = WebApplicationContextUtils.getWebApplicationContext(servletContext);
        cbrConfig = (Map<String, String>) context.getBean("cbrConfig");
    }

    public CbRmbSocketThread(ServerSocket serverSocket, ServletContext servletContext) {
        this.servletContext = servletContext;
        init();
        logger.error("server socket port : "+Integer.valueOf(cbrConfig.get("gopay.socket.port")));
        if (serverSocket == null) {
            try {
                this.serverSocket = new ServerSocket(Integer.valueOf(cbrConfig.get("gopay.socket.port")));
            } catch (IOException e) {
                e.printStackTrace();
            }
        }
    }

    @Override
    public void run() {
        logger.error("********** cbrmb service start CbRmbSocketThread ");
        while (!this.isInterrupted()) {
            try {
               Socket socket = serverSocket.accept();
               String ignoreIps=cbrConfig.get("gopay.ccb.ignore.ip");
               if (socket != null) {
                	String ip=socket.getInetAddress().toString();
                	if(!ignoreIps.contains(ip)){
                		logger.error("socket数据信息:socket receive data :"+socket.toString());
                        new CbRmbProcessSocketData(socket, this.servletContext).start();
                	}
                }

            } catch (IOException e) {
            	logger.error("ccb error:"+e);
            }

        }
    }

    public void closeServerSocket() {

        try {
            if (serverSocket != null && !serverSocket.isClosed()) {
                serverSocket.close();
            }
        } catch (IOException e) {
            e.printStackTrace();
        }
    }

	public Map<String, String> getCbrConfig() {
		return cbrConfig;
	}

	public void setCbrConfig(Map<String, String> cbrConfig) {
		this.cbrConfig = cbrConfig;
	}
    
    

}
